package com.yst.sqlbuilder;

import com.yst.lambda.TableFieldFunc;

import java.util.Map;
import java.util.Objects;

public class SQLFieldLike<T> extends SQLFieldExp<T> implements ISQLFieldExpression<T>{

    public enum LikeMode{
        LM_LEFT,
        LM_RIGHT,
        LM_ALL,
        ;
    }

    public SQLFieldLike(IAliasExpression tableAlias, TableFieldFunc<T, ?> field) {
        super(tableAlias, field);
    }

    public SQLFieldLike(TableFieldFunc<T, ?> field, IAliasExpression tableAlias) {
        super(field, tableAlias);
    }

    private Object value;
    public SQLFieldLike<T> setValue(Object value){
        this.value=value;
        return this;
    }

    private LikeMode likeMode;
    public SQLFieldLike<T> setLikeMode(LikeMode likeMode){
        this.likeMode=likeMode;
        return this;
    }

    @Override
    public String generateExpression(GenerateParam param) {
        if (Objects.isNull(value)) return "";
        String strValue=value.toString();
        boolean needSetQuotation=true;
        if (value instanceof SQLParam){
            needSetQuotation=false;
            strValue=((SQLParam<?>) value).generateExpression(param);
        }
        SQLSafe.getInstance().checkValue(strValue);
        switch (likeMode){
            case LM_ALL:
                return getRealField().concat(" ").concat(Symbol.LIKE.symbol).concat(" ")
                    .concat(needSetQuotation?"'%":"%")
                    .concat(String.format("%s", strValue))
                    .concat(needSetQuotation?"%'":"%");
            case LM_RIGHT:
                return getRealField().concat(" ").concat(Symbol.LIKE.symbol).concat(" ")
                    .concat(needSetQuotation?"'%":"%")
                    .concat(String.format("%s", strValue))
                    .concat(needSetQuotation?"'":"");
            default:
                return getRealField().concat(" ").concat(Symbol.LIKE.symbol).concat(" ")
                    .concat(needSetQuotation?"'":"")
                    .concat(String.format("%s", strValue))
                    .concat(needSetQuotation?"%'":"%");
        }
    }
}
